package com.dd.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.dd.entity.*;
import com.dd.util.PageList;

public class DdCommentDAO  extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(DdCommentDAO.class);
	public void saveOrUpdate(DdComment transientInstance) {
		log.debug("saving DdComment instance");
		try {
			getHibernateTemplate().saveOrUpdate(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	public void delete(DdComment persistentInstance) {
		log.debug("deleting DdComment instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}
	

	public DdComment findById(java.lang.Integer id) {
		log.debug("findById DdComment with id: " + id);
		try {
			DdComment instance = (DdComment) getHibernateTemplate().get(
					"com.dd.entity.DdComment", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public List findByUserId(java.lang.Integer uid) {
		log.debug(" findByUserId with id: " + uid);
		try {
			return getHibernateTemplate().find("from DdComment where userid="+uid +" order by id  desc");
			
		} catch (RuntimeException re) {
			re.printStackTrace();
			return null;
		}
	}
	
	public List findByShopid(int shopid) {
		log.debug("findByShopid ");
		try {
			return getHibernateTemplate().find("from DdComment where shopid="+shopid+" and types=1");
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public PageList findByShopid(int shopid,int pageNo, int pageSize) {
		log.debug("findDdComment page");
		try {
			PageList pl = new PageList();
			String queryString = "from DdComment where types=1 and  shopid="+shopid;
					
			String maxsizeStr = ("select count(*) " + queryString);
			Query q = this.getSession().createQuery(maxsizeStr);
			int max = 0;
			List l = q.list();
			if (l != null && !l.isEmpty()) {
				max = (Integer) l.get(0);
			}
			q = this.getSession().createQuery("from DdComment where types=1 and shopid="+shopid+" order by id desc");
			q.setFirstResult((pageNo - 1) * pageSize);
			q.setMaxResults(pageSize);
			List list = q.list();
			pl.addAll(list);
			pl.setTotalCount(max);
			return pl;
		} catch (Exception re) {
			log.error("get failed", re);
			re.printStackTrace();
			return new PageList();
		}
	}
	
}
